package com.leyou.user.service;

import com.leyou.common.constant.LyConstants;
import com.leyou.common.constant.MQConstants;
import com.leyou.common.exception.domain.ExceptionEnum;
import com.leyou.common.exception.domain.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.user.domain.User;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.mapper.UserMapper;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    public Boolean checkUserNameAndPhone(String data, Integer type) {
        User record = new User();
        switch (type) {
            case 1:
                record.setUsername(data);
                break;
            case 2:
                record.setPhone(data);
                break;
            default:
                throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        int count = userMapper.selectCount(record);
        return count!=1;
    }

    public void sendPhoneCheckCode(String phone) {
        //生成6位短信验证码
        String code = RandomStringUtils.randomNumeric(6);
        //存入redis，实际开发过期时间五分钟内
        redisTemplate.opsForValue().set(LyConstants.PHONE_CODE+phone, code, 10, TimeUnit.HOURS);
        //短信发送给用户，这里采用异步
        Map<String, String> codeMap = new HashMap<>();
        codeMap.put("phone", phone);
        codeMap.put("code", code);
        amqpTemplate.convertAndSend(MQConstants.Exchange.SMS_EXCHANGE_NAME,
                MQConstants.RoutingKey.VERIFY_CODE_KEY,
                codeMap);
    }

    /**
     * 注册业务
     * @param user
     * @param code
     */
    public void register(User user, String code) {
        //获取redis中的验证码
        String redisCode = redisTemplate.opsForValue().get(LyConstants.PHONE_CODE + user.getPhone());
        //比对验证码是否正确
        if(!StringUtils.equals(redisCode, code)){
            throw new LyException(ExceptionEnum.INVALID_VERIFY_CODE);
        }
        //密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        //入库
        int count = userMapper.insertSelective(user);
        if(count!=1){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    public UserDTO findByUsernameAndPassword(String username, String password) {
        //先根据用户名查询用户
        User record = new User();
        record.setUsername(username);
        User user = userMapper.selectOne(record);
        if(user==null){
            return null;
        }
        //再比对密码
        boolean isTrue = passwordEncoder.matches(password, user.getPassword());
        if(isTrue){
            return BeanHelper.copyProperties(user, UserDTO.class);
        }
        return null;
    }

    //*

    public UserDTO findByUserName(String usernam) {
        User user = new User();
        user.setUsername(usernam);
        List<User> list
                = userMapper.select(user);
        if (CollectionUtils.isEmpty(list)){
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        UserDTO userDTO = BeanHelper.copyProperties(list.get(0), UserDTO.class);
        return userDTO;
    }
}
